package com.demo111_判断是否是平衡二叉树;

/**
 * 前序遍历, 好慢 , 感觉这样.
 */
class TreeNode {
    int val ;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}
public class Solution {
    public boolean isBalanced(TreeNode root) {

        return check(root);
    }

    private boolean check(TreeNode root) {
        if (root==null){
            return true;
        }
        int left=dfs(root.left);
        int right=dfs(root.right);
        boolean result=  Math.abs(left-right)<=1;
        if (result){
            boolean leftchild = check(root.left);
            boolean rightchild = check(root.right);

            result=leftchild&&rightchild;
        }
        return result;
    }

    private int dfs(TreeNode root) {
        if (root==null){
            return 0;
        }
        int left=dfs(root.left);
        int right=dfs(root.right);
        return Math.max(left,right)+1;
    }
}
